
import Cookies from 'js-cookie'
import { resetRouter } from '@/router'
import Vue from 'vue'
import { TOKEN_KEY, USER_INFO_KEY } from '@/constant/common'
// const userInfoStr = getUserInfo()
// const userInfo = userInfoStr && JSON.parse(userInfoStr)
// const { account = '', name = '', forceChangePassword, id } = userInfo || {}
const state = {
  token: Cookies.get(TOKEN_KEY) || '',
  // 用户信息
  userInfo: JSON.parse(localStorage.getItem(USER_INFO_KEY)) || {}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    if (token && token !== '') {
      Cookies.set(TOKEN_KEY, token)
    } else {
      Cookies.remove(TOKEN_KEY)
    }
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    if (userInfo) {
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
    } else {
      localStorage.removeItem(USER_INFO_KEY)
    }
  }

}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      Vue.prototype.$api.system.user.login(username, password).then(response => {
        const { account, name, token, forceChangePassword, id } = response.data
        commit('SET_TOKEN', token)
        commit('SET_USER_INFO', { account, name, forceChangePassword, id })

        // 登录成功，启动websocket连接
        Vue.prototype.$webSocket.init()

        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  // 清除 token(vuex & cookie)
  // 清除 router(vue router 和 vuex router)
  // 清除 button权限(vuex button 和 session)
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      Vue.prototype.$api.system.user.logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_USER_INFO', {})

        // 关闭websocket连接
        Vue.prototype.$webSocket.close()

        // 重置vue router对象
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      }).finally(() => {

      })
    })
  },
  // 强制修改密码之后，重新给标志位赋值
  setForceChangePassword({ commit, state }, forceChangePassword) {
    return new Promise(resolve => {
      const userInfo = state.userInfo
      userInfo.forceChangePassword = forceChangePassword
      commit('SET_USER_INFO', userInfo)
      resolve()
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
